<template>
  <div class="trad-box quotebg radius-8">
    <!-- 搜索筐 -->
    <div class="search bibiinput">
      <el-input
        v-model="state.stockname"
        :placeholder="$t('exchange.inquire')"
        v-on:keyup.enter="search"
      >
        <template #prefix>
          <img
            style="width:16px;margin-top: 14px;display: block;"
            @click="search"
            src="@/assets/theme1/search.png"
            alt
          />
        </template>
      </el-input>
    </div>
    <div class="trad-tabbox flex js-ar point text-bold quotet3 text-14">
      <div
        class="trad-tab"
        @click="changeTab(1)"
        :class="{ 'tabactive text-bolder quotet2': tabActive === 1 }"
      >
        {{ $t("exchange.selfSelect") }}
      </div>
      <div
        class="trad-tab"
        @click="changeTab(2)"
        :class="{ 'tabactive text-bolder quotet2': tabActive === 2 }"
      >
        {{ $t("stock.USstocks") }}
      </div>
      <div
        class="trad-tab"
        @click="changeTab(3)"
        :class="{ 'tabactive text-bolder quotet2': tabActive === 3 }"
      >
        {{ $t("stock.HKstocks") }}
      </div>
      <div
        class="trad-tab"
        @click="changeTab(4)"
        :class="{ 'tabactive text-bolder quotet2': tabActive === 4 }"
      >
        {{ $t("stock.newEnergy") }}
      </div>
    </div>
    <div
      class="trad-all1 customer-scroll"
      v-loading="state.loading"
      :element-loading-background="
        themeType === 'night'
          ? 'rgba(0, 0, 0, 0.6)'
          : 'rgba(255, 255, 255, 0.6)'
      "
    >
      <div
        class="trad quoteline point flex align-center js-sp"
        v-for="(item, index) in state.tradList"
        @click="changeTrading(item)"
        :class="{
          'trading-active':
            $store.state.exchange.stock_lever_data?.id === item.id,
        }"
        :key="index"
      >
        <div class="mb-6 text-left text-14 family-d">
          <div class="mb-10">
            <svg-icon
              data-_icon-name="ic_icon_star_off"
              class="text-20 mr-5"
              @click.stop="changeadd(item.id, item.is_user_stock_lever)"
              v-if="!item.is_user_stock_lever"
            ></svg-icon>
            <svg-icon
              class="text-20 mr-5"
              data-_icon-name="ic_icon_star_on"
              @click.stop="changeadd(item.id, item.is_user_stock_lever)"
              v-else
            ></svg-icon>
            <span class="quotet2 text-bolder text-14">{{
              item.stock_name
            }}</span>
          </div>
          <div class="flex align-center js-st">
            <div
              class="share-color text-10 tag us"
              v-if="item.stock_type === 1"
            >
              US
            </div>
            <div
              class="share-color text-10 tag hk"
              v-if="item.stock_type === 2"
            >
              HK
            </div>
            <div class="text-12 color_42 ml-8">{{ item.stock_code }}</div>
          </div>
        </div>
        <div class="text-16 textperson-t2  family-d text-medium text-right">
          <div class="mb-10">{{ $currency(item.close_price) }}</div>
          <div
            :class="
              item.increase < 0
                ? 'text-green'
                : item.increase == 0
                ? 'quotet3'
                : 'text-red'
            "
          >
            {{ (item.increase * 100).toFixed(2) }}%
          </div>
        </div>
        <!-- <div class="flex js-sp text-8 quotet3">
          <span>{{ $t("exchange.closePrice") }}</span>
          <span>{{ $t("deal.increase") }}</span>
        </div> -->
      </div>
      <div
        class="add flex js-ct align-center"
        v-if="state.tradList.length === 0"
      >
        <el-button type="primary" @click="changeTab(2)">{{
          $t("exchange.addOptional")
        }}</el-button>
      </div>
    </div>
    <!-- 监听table滚动条触底 -->
    <Tradscroll @scroll="tableScroll" />
    <!-- websocket -->
    <!-- <Websocket
      :timeout="3000"
      name="涨幅"
      socket_type="RANKING"
      @change="onMessage"
    /> -->
  </div>
</template>

<script>
import {
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  onBeforeUnmount,
  computed,
} from "vue";
import { useStore } from "vuex";
// import Websocket from "@/components/websocket/WebSocket";
import { LoginInterception, decimalDigitsInputFilter } from "@/utils/common";
import { stockPage, stockUserCurrencyMatchListSimple } from "@/api/stock";
import { addUserCurrencyMatch, deleteUserCurrencyMatch } from "@/api/currency";
import Tradscroll from "@/components/tradscroll/index.vue";

export default {
  name: "stockLeverTrading",
  components: { Tradscroll },
  props: { currencyId: Number },
  emits: ["tradingNowData"],
  setup(props, { emit }) {
    const $store = useStore();
    const tabActive = ref($store.state.user.stockLevertradingtab);
    const changeTab = (i) => {
      refresh();
      tabActive.value = i;
      $store.commit("user/SET_TRADING_TAB", { type: "stockLever", active: i });
      getList();
    };
    const {
      appContext: {
        app: {
          config: { globalProperties },
        },
      },
    } = getCurrentInstance();
    const { $websocketTool } = globalProperties;
    const state = reactive({
      timer: null,
      tradList: [],
      param: { page: 0, limit: 10 },
      loading: false,
      copyTradList: [],
      total: 0,
    });
    const themeType = computed(() => $store.state.exchange.theme);
    const islogin = computed(() => {
      return $store.state.user.token ? true : false;
    });
    const gettrading = computed(() => {
      return $store.state.exchange?.stock_lever_data;
    });
    onMounted(() => {
      refresh();
      getList();
      state.timer = setInterval(() => {
        if ($websocketTool.ws && $websocketTool.ws.readyState == 1) {
          clearInterval(state.timer);
          state.timer = null;
          handleMsg();
        }
      }, 3000);
      document.addEventListener("visibilitychange", visibilityFn);
    });
    const refresh = () => {
      state.param = { page: 0, limit: 10 };
      state.tradList = [];
      state.copyTradList = [];
      state.total = 0;
    };
    // table滚动条触底
    const tableScroll = () => {
      if (state.total > state.tradList.length) {
        state.param.page = state.param.page + 1;
        getList();
      }
    };
    // 查询股票
    const search = () => {
      let array = [];
      if (state.stockname) {
        array = state.copyTradList.filter((item) => {
          return (
            item.stock_name.indexOf(state.stockname) > -1 ||
            item.stock_code.indexOf(state.stockname) > -1
          );
        });
      } else {
        array = state.copyTradList;
      }

      state.tradList = array;
    };
    const visibilityFn = () => {
      // 用户息屏、或者切到后台运行 （离开页面）
      if (document.visibilityState === "hidden") {
        // closeWsMessage();
        console.log("hidden");
      }
      // 用户打开或回到页面
      console.log(document.visibilityState);
      if (document.visibilityState === "visible") {
        if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
          handleMsg();
        }
      }
    };
    const handleMsg = () => {
      $websocketTool?.ws.send(
        JSON.stringify({
          socket_type: "STOCKRANKING",
          subscribed: 1,
        })
      );
      $websocketTool.ws.onmessage = function(res) {
        const message = JSON.parse(res.data);
        if (message.type === "STOCKRANKING") {
          onMessageTrading(message);
        }
      };
    };
    const closeMsg = (msg) => {
      if ($websocketTool?.ws && $websocketTool.ws.readyState == 1) {
        $websocketTool?.ws.send(JSON.stringify(msg));
      }
    };
    // 更换股票
    const changeTrading = (item) => {
      console.log(item);
      const param = {
        id: item.id,
      };
      state.loading = true;
      $store
        .dispatch("exchange/stockDetail", param)
        .then((data) => {
          $store.commit("exchange/SET_STOCK_LEVER", data);
          $store.commit("exchange/SET_STOCK_LEVER_ID", data.id);
          state.loading = false;
          const nowData = {
            high_price: data.high_price,
            increase_value: data.increase,
            low_price: data.low_price,
            now_price: data.close_price,
            transaction_amount: data.transaction_amount,
          };
          emit("tradingNowData", nowData);
        })
        .catch((err) => {
          state.loading = false;
          console.log(err);
        });
    };
    // 获取交易对列表
    const getList = async () => {
      state.loading = true;
      const requestfun =
        tabActive.value === 1 ? stockUserCurrencyMatchListSimple : stockPage;
      if (tabActive.value === 3) {
        state.param.stock_type = 2;
      } else if (tabActive.value === 2) {
        state.param.stock_type = 1;
      } else if (tabActive.value === 4) {
        state.param.stock_type = 3;
      } else {
        state.param.stock_type = null;
      }
      state.param.type = tabActive.value === 1 ? 5 : 2;
      await requestfun(tabActive.value === 1 ? state.param.type : state.param)
        .then((res) => {
          state.loading = false;
          let comondata = {};
          if (tabActive.value != 1) {
            state.tradList = [...state.tradList, ...res.data.items];
            state.copyTradList = [...state.copyTradList, ...res.data.items];
            state.total = res.data.total;
            let resStock = res.data.items.findIndex((ele) => {
              return ele.id === gettrading.value?.id;
            });
            if (
              !gettrading.value?.id ||
              !$store.state.exchange.stock_lever_data_id ||
              resStock < 0
            ) {
              changeTrading(res.data.items[0]);
            } else {
              res.data.items.forEach((item) => {
                if (item.id === gettrading.value?.id) {
                  // comondata = item;
                  changeTrading(item);
                  // console.log("comondata", comondata);
                }
              });
            }
          } else {
            state.tradList = [...res.data];
            state.copyTradList = [...res.data];
            if (
              !gettrading.value?.id ||
              !$store.state.exchange.stock_lever_data_id
            ) {
              changeTrading(res.data[0]);
            } else {
              res.data.forEach((item) => {
                if (item.id === gettrading.value?.id) {
                  // comondata = item;
                  changeTrading(item);
                  // console.log("comondata", comondata);
                }
              });
            }
          }
          if (comondata) {
            const nowData = {
              high_price: comondata.high_price,
              increase_value: comondata.increase,
              low_price: comondata.low_price,
              now_price: comondata.close_price,
              transaction_amount: comondata.transaction_amount,
            };
            emit("tradingNowData", nowData);
          }
        })
        .catch(() => {
          state.loading = false;
        });
    };
    // 更换自选
    const changeadd = (id, ischeck) => {
      const requestfun = ischeck
        ? deleteUserCurrencyMatch
        : addUserCurrencyMatch;
      state.loading = true;
      requestfun({ currency_match_id: id, currency_match_type: 5 })
        .then((res) => {
          state.loading = false;
          if (res.code === 200) {
            refresh();
            getList();
          }
        })
        .catch(() => {
          state.loading = false;
        });
    };
    // websocket推送数据
    const onMessageTrading = (val) => {
      let data = state.tradList;
      data.forEach((item) => {
        if (item.id === val.stockId) {
          item.increase = val.increase_data.increase_value;
          item.close_price = val.increase_data.now_price;
        }
      });
      state.tradList = data;
    };
    onBeforeUnmount(() => {
      document.removeEventListener("visibilitychange", visibilityFn);
      if (state.timer) {
        clearInterval(state.timer);
        state.timer = null;
      }
      closeMsg({
        socket_type: "STOCKRANKING",
        subscribed: 0,
      });
    });
    return {
      tabActive,
      changeTab,
      state,
      getList,
      changeadd,
      changeTrading,
      onMessageTrading,
      handleMsg,
      closeMsg,
      themeType,
      decimalDigitsInputFilter,
      islogin,
      search,
      LoginInterception,
      tableScroll,
      refresh,
      gettrading,
    };
  },
};
</script>

<style scoped lang="less">
.trad-box {
  width: 100%;
  // height: 775px;
  // box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}

.add {
  width: 100%;
  height: 100%;
}
.trad-tabbox {
  width: 100%;
  padding: 10px 10px 0;
  // border-bottom: 1px solid;
  margin-top: 24px;
  margin-bottom: 12px;
}
.trad-tab {
  min-height: 24px;
  line-height: 24px;
  position: relative;
  min-width: 65px;
  border-radius: 4px;
  padding: 0 4px;
}
.mb-6 {
  margin-bottom: 6px;
}
.mb-2 {
  margin-bottom: 2px;
}
.mb-10 {
  margin-bottom: 10px;
}
.trad {
  padding: 10px;
  box-sizing: border-box;
  border-bottom: 1px solid;
  position: relative;
  i {
    margin-inline-end: 7px;
  }
}
.trad-all1 {
  width: 100%;
  overflow-y: scroll;
  height: 410px;
  padding: 10px 0px;
}
// 搜索框
.search {
  width: 100%;
  height: 44px;
  padding: 10px;
  box-sizing: border-box;
}
.mb-2 {
  margin-bottom: 2px;
}
.tag {
  padding: 1px 4px;
  border-radius: 2px;
}
.us {
  width: 26px;
  width: 26px;
  background: #e54b4b;
}
.hk {
  width: 26px;
  background: #1987ed;
}
.ml-8 {
  margin-inline-start: 8px;
}
</style>
<style>
.bibiinput .el-input__suffix-inner,
.bibiinput .el-input__suffix {
  display: flex;
  align-items: center;
}
</style>
